package org.cweili.vehicle.service.admin

import org.cweili.vehicle.entity.Customer
import org.cweili.vehicle.service.BaseService
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.cweili.vehicle.util.Utils
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

import com.alibaba.fastjson.JSONArray

/**
 * 管理员用户服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:22:04
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class AdminCustomerService extends BaseService {

	Page<Customer> getList(String json) {
		def obj = JSON.parseObject(json)

		def type = JSON.getByte(obj, "type")
		def page = JSON.getInteger(obj, "page")

		return customerRepository.findByClassification(type, new PageRequest(page, Const.PAGE_SIZE,
		Sort.Direction.DESC, "id"))
	}

	boolean del(String json) {
		try {
			def array = JSONArray.parseArray(json)

			for (obj in array) {
				customerRepository.delete(Integer.parseInt(obj.toString()))
			}
		} catch (Exception e) {
			log.error(e + json, e)
			return false
		}
		return true
	}

	boolean save(String json) {
		def obj = JSON.parseObject(json)

		def classification = JSON.getByte(obj, "classification")
		def sex = JSON.getByte(obj, "sex")
		def id = JSON.getInteger(obj, "id")
		def phone = JSON.getString(obj, "phone")
		def number = JSON.getString(obj, "number")
		def password = JSON.getString(obj, "passwordNew")
		def name = JSON.getString(obj, "name")
		def idCard = JSON.getString(obj, "idCard")
		def joinDate = JSON.getDate(obj, "joinDateYear", "joinDateMonth", "joinDateDate")
		def birthday = JSON.getDate(obj, "birthdayYear", "birthdayMonth", "birthdayDate")

		if (id > 0 && Utils.isEmpty(number, name)) {
			return false
		} else if (0 == id && Utils.isEmpty(number, password, name)) {
			return false
		}

		def customer
		if (id > 0) {
			customer = customerRepository.findOne(id)
			if (!customer) {
				return false
			}
		} else {
			customer = new Customer()
		}
		customer.birthday = birthday
		customer.classification = classification
		customer.idCard = idCard
		customer.joinDate = joinDate
		customer.name = name
		customer.number = number
		customer.phone = phone
		customer.sex = sex
		if (!Utils.isEmpty(password)) {
			customer.password = password
		}
		return customerRepository.save(customer)
	}
}
